package com.tangsm.boot.demo.shiro.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.tangsm.boot.demo.shiro.entity.Person;
import com.tangsm.boot.demo.shiro.entity.UserInfo;

@Controller
public class IndexController {

	@Autowired
	HttpServletRequest req;

	@RequestMapping({ "/", "/index" })
	public String index() {
		UserInfo user = new UserInfo();
		user.setUsername("tangsm");
		user.setSign("123");
		req.setAttribute("user", user);

		List<Person> people = new ArrayList<>();
		Person p1 = new Person();
		p1.setName("李四");
		p1.setAge(23);
		people.add(p1);

		Person p2 = new Person();
		p2.setName("王五");
		p2.setAge(24);
		people.add(p2);

		Person p3 = new Person();
		p3.setName("赵六");
		p3.setAge(25);
		people.add(p3);

		req.setAttribute("people", people);
		return "index";
	}

	@GetMapping("/login")
	public String login() {
		return "login";
	}

	/**
	 * 登录
	 */
	@PostMapping("/doLogin")
	public String doLogin(String username, String password) {
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		try {
			SecurityUtils.getSubject().login(token);
		} catch (AuthenticationException e) {
			if (e instanceof UnknownAccountException) {
				req.setAttribute("errorMess", "用户不存在");
			} else if (e instanceof LockedAccountException) {
				req.setAttribute("errorMess", "用户被禁用");
			} else if (e instanceof IncorrectCredentialsException) {
				req.setAttribute("errorMess", "密码错误");
			} else {
				req.setAttribute("errorMess", "用户认证失败");
			}
			return "/login";
		}
		UserInfo user = new UserInfo();
		user.setUsername(username);
		user.setSign(password);
		req.setAttribute("username", username);
		req.setAttribute("password", password);
		return "redirect:/";
	}

	/**
	 * 退出登录
	 */
	@GetMapping("/logout")
	public String logout() {
		SecurityUtils.getSubject().logout();
		return "redirect:/login";
	}
}
